package com.yuwenchao.superafflatus.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.yuwenchao.superafflatus.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Api(tags = "腾讯云对象存储")
@RestController
@RequestMapping("/tx")
public class TxOssUpdateController {

    @Value("${spring.tencent.cos.app-id}")
    private String appId;
    @Value("${spring.tencent.cos.secret-id}")
    private String secretId;
    @Value("${spring.tencent.cos.secret-key}")
    private String secretKey;
    @Value("${spring.tencent.cos.bucket-name}")
    private String bucketName;
    @Value("${spring.tencent.cos.region-id}")
    private String regionId;
    @Value("${spring.tencent.cos.base-url}")
    private String baseUrl;


 public COSClient getOssClientInfo(){
     COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
     Region region = new Region(regionId);
     ClientConfig clientConfig = new ClientConfig(region);
     return new COSClient(cred, clientConfig);
 }




    @ApiOperation(value = "腾讯云图片上传")
    @PostMapping("avatar/upload")
    public R TXupload(
            @ApiParam(name = "avatar", value = "文件", required = false)
            @RequestParam("avatar") MultipartFile avatar) {

        String uploadUrl = null;
        try {
           /* COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            Region region = new Region(regionId);
            ClientConfig clientConfig = new ClientConfig(region);
            COSClient cosClient = new COSClient(cred, clientConfig);*/
            COSClient cosClient = getOssClientInfo();


            InputStream inputStream = avatar.getInputStream();

            String original = avatar.getOriginalFilename();
           // String fileName = UUID.randomUUID().toString();
           // String fileType = original.substring(original.lastIndexOf("."));
           // String newName = fileName + fileType;
            String key = "avatar/"+original;


            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,inputStream, null);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

            uploadUrl = baseUrl + "/" + key;


            // 关闭客户端(关闭后台线程)
            cosClient.shutdown();

        } catch (IOException e) {
            e.printStackTrace();
        }
            //https://afflatus-1309221527.cos.ap-nanjing.myqcloud.com/avatar/kenan.jpg


        return R.ok().message("文件上传成功").data("url", uploadUrl);

    }


    @ApiOperation(value = "腾讯云音乐上传")
    @PostMapping("music/upload")
    public R TXuploadMusic(
            @ApiParam(name = "music", value = "文件", required = false)
            @RequestParam("music") MultipartFile music) {
        String uploadUrl = null;
        try {
            /*COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            Region region = new Region(regionId);
            ClientConfig clientConfig = new ClientConfig(region);
            COSClient cosClient = new COSClient(cred, clientConfig);*/

            COSClient cosClient = getOssClientInfo();

            InputStream inputStream = music.getInputStream();
            String original = music.getOriginalFilename();
            String key = "music/"+original;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,inputStream, null);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            uploadUrl = baseUrl + "/" + key;

            // 关闭客户端(关闭后台线程)
            cosClient.shutdown();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok().message("文件上传成功").data("url", uploadUrl);

    }



    //  avatar/kenan.jpg
    @ApiOperation(value = "腾讯云图片下载")
    @PostMapping("avatar/download")
    public  R txdownload(@ApiParam(value = "文件路劲,例如:avatar/kenan.jpg",required = true)String key){

          /*  COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
            Region region = new Region(regionId);
            ClientConfig clientConfig = new ClientConfig(region);
            COSClient cosClient = new COSClient(cred, clientConfig);*/

        COSClient cosClient = getOssClientInfo();

             //下载文件到本地的路径，例如 D 盘的某个目录
            String outputFilePath = "D:\\"+key;
            File downFile = new File(outputFilePath);
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
            ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);

        // 关闭客户端(关闭后台线程)
        cosClient.shutdown();

        return R .ok().data("url",outputFilePath);
    }

    /**
     * 该方法将所有OSS音乐文件信息存入music表中
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    @ApiOperation(value = "腾讯云对象列表")
    @PostMapping("txFile/list")
    public ObjectListing listObjects(@ApiParam(value = "文件路劲,例如:/avatar,/等",required = true) String filePath) throws CosClientException, CosServiceException{
        /*COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(regionId);
        ClientConfig clientConfig = new ClientConfig(region);

        COSClient cosClient = new COSClient(cred, clientConfig);*/

        COSClient cosClient = getOssClientInfo();

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();


        // 设置 bucket 名称
        listObjectsRequest.setBucketName(bucketName);
        // 设置列出的对象名以 prefix 为前缀
        listObjectsRequest.setPrefix(filePath);   //该值可传   /    music  /avatar
        // 设置最大列出多少个对象, 一次 listobject 最大支持1000
        listObjectsRequest.setMaxKeys(1000);

        // 保存列出的结果
        ObjectListing objectListing = null;

        try {
            objectListing = cosClient.listObjects(listObjectsRequest);
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }

        // object summary 表示此次列出的对象列表
        List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
        for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
            System.out.println(cosObjectSummary);
            // 对象的 key
            String key = cosObjectSummary.getKey();
            // 对象的etag
            String etag = cosObjectSummary.getETag();
            // 对象的长度
            long fileSize = cosObjectSummary.getSize();
            // 对象的存储类型
            String storageClasses = cosObjectSummary.getStorageClass();


        }

//        if (objectListing.isTruncated()) {
//            // 表示还没有列完，被截断了
//
//            // 下一次开始的位置
//            String nextMarker = objectListing.getNextMarker();
//        }

// 确认本进程不再使用 cosClient 实例之后，关闭之
        cosClient.shutdown();


        return objectListing;

    }

    @ApiOperation(value = "腾讯云文件夹列表")
    @PostMapping("dir/list")
    public  R getFileList(){

     /*   COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(regionId);
        ClientConfig clientConfig = new ClientConfig(region);

        COSClient cosClient = new COSClient(cred, clientConfig);*/

        COSClient cosClient = getOssClientInfo();


        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();

        listObjectsRequest.setBucketName(bucketName);

// prefix 表示列出的对象名以 prefix 为前缀
// 这里填要列出的目录的相对 bucket 的路径
        listObjectsRequest.setPrefix("/");

// delimiter 表示目录的截断符, 例如：设置为 / 则表示对象名遇到 / 就当做一级目录）
        listObjectsRequest.setDelimiter("/");
// 设置最大遍历出多少个对象, 一次 listobject 最大支持1000
        listObjectsRequest.setMaxKeys(1000);

// 保存每次列出的结果
        ObjectListing objectListing = null;

        do {
            try {
                objectListing = cosClient.listObjects(listObjectsRequest);
            } catch (CosServiceException e) {
                e.printStackTrace();
                return R.error();
            } catch (CosClientException e) {
                e.printStackTrace();
                return R.error();
            }

            // 这里保存列出来的子目录
            List<String> commonPrefixs = objectListing.getCommonPrefixes();
            for (String commonPrefix : commonPrefixs) {
                System.out.println(commonPrefix);
            }
            // 这里保存列出的对象列表
            List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();

            for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
                System.out.println("列表对象:"+cosObjectSummary);
                // 对象的 key
                String key = cosObjectSummary.getKey();
                // 对象的etag
                String etag = cosObjectSummary.getETag();
                // 对象的长度
                long fileSize = cosObjectSummary.getSize();
                // 对象的存储类型
                String storageClasses = cosObjectSummary.getStorageClass();
            }

            // 标记下一次开始的位置
            String nextMarker = objectListing.getNextMarker();
            listObjectsRequest.setMarker(nextMarker);
        } while (objectListing.isTruncated());

// 确认本进程不再使用 cosClient 实例之后，关闭之
        cosClient.shutdown();


        return R.ok().data("objectListing",objectListing);
    }

    // 传值 key ="music/红日 (李克勤).mp3"
    @ApiOperation(value = "腾讯云删除文件")
    @GetMapping("delete/file")
    public  R deleteFile(@ApiParam(value = "文件路劲,例如:music/a.mp3",required = true) String key){
        //bucketName ="afflatus-1309221527";
        //key ="music/红日 (李克勤).mp3"
      /*  COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(regionId);
        ClientConfig clientConfig = new ClientConfig(region);
        COSClient cosClient = new COSClient(cred, clientConfig);*/
        COSClient cosClient = getOssClientInfo();

        try {
            cosClient.deleteObject(bucketName, key);
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        return R.ok();
    }



}
